package com.github.wxiaoqi.security.biz.biz.community;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.auth.common.util.SnowFlake;
import com.github.wxiaoqi.security.biz.entity.commen.Comment;
import com.github.wxiaoqi.security.biz.entity.commen.Favort;
import com.github.wxiaoqi.security.biz.entity.community.CommunityViewpoint;
import com.github.wxiaoqi.security.biz.mapper.CommentMapper;
import com.github.wxiaoqi.security.biz.mapper.CommunityViewpointMapper;
import com.github.wxiaoqi.security.biz.mapper.FavortMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.cms.request.CmsQueryViewPointParam;
import com.github.wxiaoqi.security.common.cms.request.CmsSaveViewPointParam;
import com.github.wxiaoqi.security.common.cms.request.CmsViewPointRequestParam;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.ResponseHelper;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;



/**
 * 
 *
 * @author chj
 * @email 
 * @date 2018-07-09 14:10:44
 */
@Slf4j
@Service
public class CommunityViewpointBiz extends BaseBiz<CommunityViewpointMapper,CommunityViewpoint> {
	
	@Autowired
	private FavortMapper favortMapper;
	@Autowired
	private CommentMapper commentMapper;
	
	
	/**
	 * 查询观点列表
	 * @param param
	 * @return
	 */
	public Map<String, Object> queryViewPoint(CmsQueryViewPointParam param) {
		 log.info("查询观点列表，请求参数。。。{}"+param);
		 Example example = new Example(CommunityViewpoint.class);
		 Criteria criteria = example.createCriteria();
		 criteria.andEqualTo("viewType", param.getViewType());
		 criteria.andEqualTo("merchantId", param.getMerchantId());
		 criteria.andEqualTo("platformId",param.getPlatformId());
		 
		 example.setOrderByClause("point_time desc");
		 Integer page = param.getPage();
		 Integer limit = param.getLimit();
		 Map<String, Object> reqMap = new HashMap<>();
		 reqMap.put("page", page);
		 reqMap.put("limit", limit);
		 Query query = new Query(reqMap);
		 Page<CommunityViewpoint> pointResult = PageHelper.startPage(query.getPage(), query.getLimit());
		 List<CommunityViewpoint> pointList = mapper.selectByExample(example);
		 if(pointList != null && pointList.size() > 0) {
			 for (CommunityViewpoint communityViewpoint : pointList) {
				if (communityViewpoint != null) {
					Date time = communityViewpoint.getPointTime();
					SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//
					String fromDate = simpleFormat.format(time);
					String toDate = simpleFormat.format(new Date());
					try {
						long from = simpleFormat.parse(fromDate).getTime();
						long to = simpleFormat.parse(toDate).getTime();
						int minutes = (int) ((to - from)/(1000 * 60));
						if (minutes < 1) {
							communityViewpoint.setDiffTime("刚刚");
						}else if(minutes <= 60){
							//如果小于60分钟就显示分钟
							communityViewpoint.setDiffTime(String.valueOf(minutes)+"分钟前");
						}else if(minutes > 60 && minutes <= 60*24){
							//如果大于60分钟小于24小时显示小时
							int hours = (int) ((to - from)/(1000 * 60 * 60));
							communityViewpoint.setDiffTime(String.valueOf(hours)+"小时前");
						}else{
							//大于24小时显示天
							int days = (int) ((to - from)/(1000 * 60 * 60 * 24));
							communityViewpoint.setDiffTime(String.valueOf(days)+"天前");
						}
					} catch (ParseException e) {
						e.printStackTrace();
					}
					
					Example example1 = new Example(Favort.class);
					Criteria criteria1 = example1.createCriteria();
					criteria1.andEqualTo("merchantId", param.getMerchantId());
					criteria1.andEqualTo("platformId",param.getPlatformId());
					criteria1.andEqualTo("favortStatus",1);
					criteria1.andEqualTo("pointId",communityViewpoint.getId());
					example1.setOrderByClause("create_time desc");
					List<Favort> favorts = favortMapper.selectByExample(example1);
					if (favorts != null && favorts.size() > 0) {
						List<String> strings = new ArrayList<>();
						for (Favort favort : favorts) {
							strings.add(favort.getCustomerId());
						}
						String str=String.join(",", strings);
						communityViewpoint.setFavort(str);
					}
					communityViewpoint.setFavorts(favorts);
					communityViewpoint.setFavortCount(favorts.size());
					
					Example example2 = new Example(Comment.class);
					Criteria criteria2 = example2.createCriteria();
					criteria2.andEqualTo("merchantId", param.getMerchantId());
					criteria2.andEqualTo("platformId",param.getPlatformId());//commentModuleNo
					criteria2.andEqualTo("commentModuleNo",param.getViewType());
					criteria2.andEqualTo("commentTargetId",communityViewpoint.getId());
					example2.setOrderByClause("comment_time asc");
					List<Comment> comments = commentMapper.selectByExample(example2);
					communityViewpoint.setComments(comments);
					communityViewpoint.setCommentCount(comments.size());
				}
			}
		 }
		 TableResultResponse<CommunityViewpoint> pointTable = new TableResultResponse<>(pointResult.getTotal(), pointList);
		 log.info("观点列表。。。{}"+pointList);
		 Map<String, Object> respMap = new java.util.HashMap<>();
		 respMap.put("code", ResponseCode.OK.getCode());
		 respMap.put("msg", ResponseCode.OK.getMessage());
		 respMap.put("success", true);
		 respMap.put("points", pointTable);
		 return respMap;
	}
	
	/**
	 * 添加观点
	 * @param param
	 * @return
	 */
	public Map<String, Object> addViewPoint(CmsSaveViewPointParam param) {
		Long id = SnowFlake.getId();
		CommunityViewpoint viewpoint = new CommunityViewpoint();
		
		viewpoint.setPointText(param.getPointText());
		viewpoint.setCustomerId(param.getCustomerId());
		viewpoint.setFavortCount(0);
		viewpoint.setCommentCount(0);
		viewpoint.setId(String.valueOf(id));
		viewpoint.setPointTime(new Date());
		viewpoint.setViewType(param.getViewType());
		viewpoint.setNickName(param.getNickName());
		viewpoint.setAvatarUrl(param.getAvatarUrl());
		viewpoint.setPointImg(param.getImgFileName());
		viewpoint.setMerchantId(param.getMerchantId());
		viewpoint.setPlatformId(param.getPlatformId());
		viewpoint.setPointAddress(param.getPointAddress());
		viewpoint.setIsPrivate(param.getIsPrivate());
		viewpoint.setSaleName(param.getSaleName());
		viewpoint.setSaleSex(param.getSaleSex());
		try {
			mapper.insert(viewpoint);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, Object> respMap = new HashMap<>();
		respMap.put("code", ResponseCode.OK.getCode());
		respMap.put("msg", ResponseCode.OK.getMessage());
		respMap.put("success", true);
		return respMap;
	}
	
	/** 
	 * 查询观点详情
	 * @param param
	 * @return
	 */
	public Map<String, Object> queryViewpointInfo(CmsQueryViewPointParam param) {
		Map<String, Object> respMap = new HashMap<>();
		String merchantId = param.getMerchantId();
		String platformId = param.getPlatformId();
		String id = param.getViewpointId();
		CommunityViewpoint viewpoint = mapper.selectByPrimaryKey(id);
		if (viewpoint != null) {
			Date time = viewpoint.getPointTime();
			SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//
			String fromDate = simpleFormat.format(time);
			String toDate = simpleFormat.format(new Date());
			try {
				long from = simpleFormat.parse(fromDate).getTime();
				long to = simpleFormat.parse(toDate).getTime();
				int minutes = (int) ((to - from)/(1000 * 60));
				if(minutes <= 60){
					//如果小于60分钟就显示分钟
					viewpoint.setDiffTime(String.valueOf(minutes)+"分钟前");
				}else if(minutes > 60 && minutes <= 60*24){
					//如果大于60分钟小于24小时显示小时
					int hours = (int) ((to - from)/(1000 * 60 * 60));
					viewpoint.setDiffTime(String.valueOf(hours)+"小时前");
				}else{
					//大于24小时显示天
					int days = (int) ((to - from)/(1000 * 60 * 60 * 24));
					viewpoint.setDiffTime(String.valueOf(days)+"天前");
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			Example example1 = new Example(Favort.class);
			Criteria criteria1 = example1.createCriteria();
			criteria1.andEqualTo("merchantId", param.getMerchantId());
			criteria1.andEqualTo("platformId",param.getPlatformId());
			criteria1.andEqualTo("favortStatus",1);
			criteria1.andEqualTo("pointId",viewpoint.getId());
			example1.setOrderByClause("create_time desc");
			
			Example example2 = new Example(Comment.class);
			Criteria criteria2 = example2.createCriteria();
			criteria2.andEqualTo("merchantId", param.getMerchantId());
			criteria2.andEqualTo("platformId",param.getPlatformId());//commentModuleNo
			criteria2.andEqualTo("commentModuleNo","02");
			criteria2.andEqualTo("commentType","1");
			criteria2.andEqualTo("commentTargetId",viewpoint.getId());
			example2.setOrderByClause("comment_time asc");
			List<Comment> comments = commentMapper.selectByExample(example2);
			if (comments != null && comments.size() > 0) {
				for (Comment comment : comments) {
					Comment comment1 = new Comment();
					comment1.setCommentModuleNo("02");
					comment1.setParentId(comment.getId());
					List<Comment> list = commentMapper.select(comment1);
					comment.setComments(list);
				}
			}
			
			viewpoint.setComments(comments);
			viewpoint.setCommentCount(comments.size());
			
			respMap.put("code", ResponseCode.OK.getCode());
			respMap.put("msg", ResponseCode.OK.getMessage());
			respMap.put("info", viewpoint);
			respMap.put("success", true);
		}else {
			respMap.put("success", false);
			return ResponseHelper.success(respMap, null, "01", "观点不存在");
		}
		return respMap;
	}
	
	
	/**
	 * 后台查询观点
	 * @param map
	 * @return
	 */
	public TableResultResponse<CommunityViewpoint> queryViewpoints(CmsQueryViewPointParam param) {
		log.info("后台查询观点列表。。。{}"+param);
		Example example = new Example(CommunityViewpoint.class);
		Criteria criteria = example.createCriteria();
		if (param.getPlatformId() != null && param.getPlatformId().length() > 0) {
			criteria.andEqualTo("platformId",param.getPlatformId());
		}
		if (param.getMerchantId() != null && param.getMerchantId().length() > 0) {
			criteria.andEqualTo("merchantId",param.getMerchantId());
		}
		if (param.getViewType() != null && param.getViewType().length() > 0) {
			criteria.andEqualTo("viewType",param.getViewType());
		}
		example.setOrderByClause("point_time desc");
		Page<CommunityViewpoint> result = PageHelper.startPage(param.getPage(), param.getLimit());
		List<CommunityViewpoint> list = mapper.selectByExample(example);
		TableResultResponse<CommunityViewpoint> table = new TableResultResponse<>(result.getTotal(), list);
		return table;
	}
	
	
	/**
	 * 删除观点
	 * @param param
	 * @return
	 */
	public Map<String, Object> deleteViewpoint(CmsViewPointRequestParam param) {
		log.info("删除观点。。。{}"+param);
		Map<String, Object> respMap = new HashMap<>();
		try {
			String id = param.getId();
			CommunityViewpoint comment = mapper.selectByPrimaryKey(id);
			if (comment != null) {
				mapper.delete(comment);
				respMap.put("code", "00");
				respMap.put("msg", "删除成功");
			}else {
				respMap.put("code", "01");
				respMap.put("msg", "观点不存在");
			}
		} catch (Exception e) {
			respMap.put("code", "01");
			respMap.put("msg", "操作异常");
		}
		return respMap;
	}
	
	
}